import React, { useState, useEffect, useRef } from "react";
import _ from 'lodash'
import styles from "./index.less";
import { getVariousSingers } from "@/api";
import MyImg from '@/components/myimg' 
import LoadingPage from '@/components/loadingPage'
import imgUnload from '@/assets/img/music-unload.png'
interface propstype {
  parentelement: any
}
const Singer: React.FC<propstype> = ({ parentelement }) => {
  const img_artlist =
    "https://p2.music.126.net/MJdmNzZwTCz0b4IpHJV6Wg==/109951162865487429.jpg?param=113y113";
  //调用歌手列表接口 的参数，依次代表area，type，initial 对应arttypes
  const [arrpara, setArrpara] = useState<any>([-1, -1, -1]);
  const [singerLists, setSingerLists] = useState<Array<any>>([]);
  const [isLoading,setIsLoading] = useState<boolean>(true)
  const loadOnecCount: number = 48
  const singersPage = useRef(null)
  let offset:number = 0
  let canRun:boolean=true
  //根据arrpara获取歌手列表
  const addLimit = ()=>{
    getVariousSingers({
      area: arrpara[0],
      type: arrpara[1],
      initial: arrpara[2],
      limit: loadOnecCount,
      offset:offset
    }).then((res:any) => {
      if (res?.artists?.length > 0) {
        offset = offset + res.artists.length
        setSingerLists((currentList)=>currentList.concat(res.artists))
        // console.log(res.artists)
      } else {
        if (parentelement) {
          parentelement.removeEventListener('scroll', loadingBottom)
        }
        setIsLoading(false)
      }
    });
  }
  const runOnceInMs = (fun: Function, ms: number) => {
    if (canRun) {
      canRun = false
      fun()
      return setTimeout(() => {
        canRun = true
      }, ms);
    }
  }
  const loadingBottom = () => {
    if (singersPage?.current?.offsetHeight && parentelement?.scrollTop -
      0.75 * (singersPage?.current?.offsetHeight - document.body.offsetHeight) >= 0) {
        runOnceInMs(addLimit,500) 
    }
  }
  useEffect(() => {    
    getVariousSingers({
      area: arrpara[0],
      type: arrpara[1],
      initial: arrpara[2],
      limit: 2*loadOnecCount
    }).then((res) => {
      offset = 2*loadOnecCount
      setSingerLists(res?.artists);
      console.log('get singers first')
    });
  }, arrpara);
  
  useEffect(() => {
    if (parentelement) {
      // React.cloneElement(parentelement,{
      //   onScroll: _.debounce(loadingBottom,1000)
      // })
      parentelement.addEventListener('scroll', loadingBottom)
    }
    return () => {
       if (parentelement) {
        parentelement.removeEventListener('scroll', loadingBottom)
        // console.log('remove bind successfully');
      } 
    }
  }, [parentelement])
  const changeSingerlist = (indexOfValuename: number, value: number | "") => {
    indexOfValuename == 0
      ? setArrpara([value, arrpara[1], arrpara[2]])
      : indexOfValuename == 1
        ? setArrpara([arrpara[0], value, arrpara[2]])
        : indexOfValuename == 2
          ? setArrpara([arrpara[0], arrpara[1], value])
          : console.log("错误：indexOfValuename：" + indexOfValuename + "不是0，1，2");
  };
  //创建检索列表 name:文本内容 value：数组的{名称=value} 作为参数获取接口
  const arttypes = [
    {
      array: [
        { name: "全部", value: -1 },
        { name: "华语", value: 7 },
        { name: "欧美", value: 96 },
        { name: "日本", value: 8 },
        { name: "韩国", value: 16 },
        { name: "其他", value: 0 },
      ],
      text: "语种",
    },
    {
      array: [
        { name: "全部", value: -1 },
        { name: "男歌手", value: 1 },
        { name: "女歌手", value: 2 },
        { name: "乐队组合", value: 3 },
      ],
      text: "分类",
    },
    {
      array: [
        { name: "热门", value: -1 },
        { name: "A", value: "A" },
        { name: "B", value: "B" },
        { name: "C", value: "C" },
        { name: "D", value: "D" },
        { name: "E", value: "E" },
        { name: "F", value: "F" },
        { name: "G", value: "G" },
        { name: "H", value: "H" },
        { name: "I", value: "I" },
        { name: "J", value: "J" },
        { name: "K", value: "K" },
        { name: "L", value: "L" },
        { name: "M", value: "M" },
        { name: "N", value: "N" },
        { name: "O", value: "O" },
        { name: "P", value: "P" },
        { name: "Q", value: "Q" },
        { name: "R", value: "R" },
        { name: "S", value: "S" },
        { name: "T", value: "T" },
        { name: "U", value: "U" },
        { name: "V", value: "V" },
        { name: "W", value: "W" },
        { name: "X", value: "X" },
        { name: "Y", value: "Y" },
        { name: "Z", value: "Z" },
        { name: "#", value: 0 },
      ],
      text: "筛选",
    },
  ];

  return (
    <div>
      <div className={styles["toppage"]}>
        {arttypes.map((item, index: number) => (
          <div 
          style={{ marginTop: '10px' }}
          key={`arttypes${item?.text}`}
          >
            <div className={styles["nameOftype"]}>{item.text}：</div>
            <div className={styles["trpage"]}>
              {item.array.map((itemIn: any) => (
                <div 
                className={styles["selections"]}
                key={`arttypes.array${itemIn?.value}`}
                >
                  {/* 每行中被选中的input有一个特殊样式：当前value===arrpara[index] 即显示 */}
                  <div className={styles["selections"]}>
                    <a className={`${styles["selection"]} 
                    ${`${itemIn.value}` === `${arrpara[index]}`
                      ? `${styles["selected"]}`
                      : ""
                      }`}
                      onClick={(ele) => {
                        ele.stopPropagation()
                        setIsLoading(true)
                        changeSingerlist(index, itemIn.value)
                      }}
                    >{itemIn.name}</a>
                  </div>
                  <span>|</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
      <div 
      className={styles["bottompage"]} 
      ref={singersPage}
      onLoad={(ele)=>{
        ele?.nativeEvent?.stopImmediatePropagation()
        // console.log('load')
        setIsLoading(false)
      }}>
        {arrpara[1] === -1 
        &&arrpara[2] === -1 
        && (
            <div className={styles["list"]}>
              <a  className={styles["aimg"]}>
                <img src={img_artlist}/>
              </a>
              <a  className={styles["aname"]}>
                歌手排行榜
              </a>
            </div>
          )}
        {singerLists.map((item: any,index:number) => (
          <div
           className={styles["list"]}
           key={`singerListsIn${index}`}
           >
            <div  className={styles["aimg"]}>
              <MyImg 
              src={item.picUrl}
              imgSize={{width:113}}
              placeholderSrc={imgUnload} 
              />
            </div>
            <a  className={styles["aname"]}>
              {item.name}
            </a>
          </div>
        ))}
        <LoadingPage isLoading={isLoading} style={{float:'left'}}/>
        <div style={{ clear: 'both' }}></div>
      </div>
    </div>
  );
};
export default Singer;
